package org.hugh.space.web.servlet;

import java.io.BufferedOutputStream;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hugh.space.entity.FileEntity;


public class FileDownloadServlet  extends BaseSpringServlet {
	
	private static final long CACHE_LIMIT = 1048576;
	
	private static final long serialVersionUID = 6098745782027999297L;
	private static final Log log = LogFactory.getLog(FileDownloadServlet.class);

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

        log.debug("get file " + request.getPathInfo());
		
			
		FileEntity file = getDao().getFileDao().getById(getId(request.getPathInfo())); 
		if (file != null) {
			sendFile(file, request, response);
		}
		else {
	        log.info("file " + request.getPathInfo() + " was not found");
			response.getWriter().append("file " + request.getPathInfo() 
					+ " was not found");
		}
	}
	
	private String getId(String pathInfo){
		String[] chain = pathInfo.split("/");
		return chain[chain.length-1];
	}
	
	private void sendFile(final FileEntity file, HttpServletRequest request,
			HttpServletResponse response) 
			throws IOException {
		
			response.setHeader("Content-type", file.getMimeType());
			response.setHeader("Content-Length", String.valueOf(file.getSize()));
			response.setHeader ("Content-Disposition", "attachment; filename=\""+file.getFilename()+"\"");

			BufferedOutputStream output = new BufferedOutputStream(
					response.getOutputStream());
			output.write(getDao().getFileDao().getFileContent(file));
			output.flush();
			output.close();
		
	}
}